<template>
  <el-dialog
    title="选择生产计划单"
    :visible="selectPrsCodeDialog"
    width="70%"
    class="prs-Mbom-select"
    @close="selectPrsCodeClose"
  >
    <div class="app-container">
      <div class="layout-box">
        <el-form :inline="true" label-width="70px" class="search-top">
          <div class="search-sub">
            <el-form-item label-width="82">
              <el-input
                v-model="searchForm.ppNumber"
                clearable
                size="small"
                placeholder="销售单号"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label-width="82">
              <el-input
                v-model="searchForm.mpCode"
                clearable
                size="small"
                placeholder="计划单号"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label-width="82">
              <el-input
                v-model="searchForm.invCode"
                clearable
                size="small"
                placeholder="物料编码"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label-width="82">
              <el-input
                v-model="searchForm.invName"
                clearable
                size="small"
                placeholder="物料名称"
                style="width: 150px"
              />
            </el-form-item>
            <el-form-item label-width="82">
              <el-date-picker
                v-model="valueDate"
                type="daterange"
                align="right"
                unlink-panels
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :picker-options="pickerOptions"
                style="width: 250px"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                v-if="detailStatus == false"
                icon="el-icon-search"
                @click="searchList('bill')"
                >搜索
              </el-button>
              <el-button
                type="primary"
                v-if="detailStatus == true"
                icon="el-icon-search"
                @click="searchList('detail')"
                >搜索
              </el-button>
            </el-form-item>
          </div>
          <div>
            <!-- <el-button
              type="primary"
              icon="el-icon-document-remove"
              size="mini"
              @click="handleContinuity"
              >{{ typeTitle }}
            </el-button> -->
            <el-button
              type="primary"
              plain
              icon="el-icon-menu"
              size="mini"
              @click="handleCheckleAll"
              v-if="detailStatus == false"
              >查询所有</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-menu"
              size="mini"
              @click="handleCheckleDetail"
              v-if="detailStatus == true"
              >查询所有</el-button
            >
          </div>
        </el-form>
        <!-- 单据列表 -->
        <el-table
          :data="billTableData"
          style="width: 100%"
          v-loading="loading"
          :height="maxHeight"
          ref="billTable"
          :expand-row-keys="expands"
          @expand-change="handleExpand"
          @row-click="clickRowHandle"
          v-if="detailStatus == false"
          row-key="mp_code"
          :key="tableKey"
        >
          <el-table-column type="expand">
            <template slot-scope="scope">
              <el-table
                :data="scope.row.list"
                style="width: 100%"
                :ref="'detailTable' + scope.row.mp_code"
                @row-click="clickRowRadio"
                border
                class="child-table"
              >
                <el-table-column prop="invCode" label="物料编码" align="center">
                </el-table-column>
                <el-table-column label="物料名称" align="center">
                  <template v-slot="scope">
                    <div>
                      <span
                        >{{ scope.row.invName }}
                        {{ scope.row.invAttribute }}</span
                      >
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="unitName"
                  label="主计量"
                  align="center"
                  width="100"
                >
                </el-table-column>
                <el-table-column
                  prop="invQuantity"
                  label="数量"
                  align="center"
                  width="150"
                >
                  <template v-slot="scope">
                    <div style="text-align: right">
                      <span>{{ scope.row.invQuantity }} </span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column width="50" align="center">
                  <template v-slot="scope">
                    <el-radio
                      v-model="successData"
                      :label="scope.row"
                      @change="radioData(scope.row)"
                    >
                      选择
                    </el-radio>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column
            prop="salesman"
            label="销售员"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="pp_number"
            label="销售单号"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column prop="pp_date" label="订单交期" align="center">
            <template v-slot="scope">
              <span>
                {{ scope.row.pp_date | inMaterTime }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="mp_code" label="计划单号" align="center">
          </el-table-column>
          <el-table-column prop="work_type" label="业务类型" align="center">
          </el-table-column>
          <el-table-column prop="invoice_date" label="单据日期" align="center">
            <template v-slot="scope">
              <span>{{ scope.row.invoice_date | inMaterTime }}</span>
            </template>
          </el-table-column>
        </el-table>
        <!-- 明细 -->
        <el-table
          style="width: 100%"
          ref="tableDetailHeight"
          :data="detailTableData"
          v-loading="detailLoading"
          :height="detailMaxHeight"
          :key="tableKey2"
          v-if="detailStatus == true"
          @row-dblclick="handleSelectDetail"
          border
        >
          <el-table-column
            prop="salesman"
            label="销售员"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="pp_number"
            label="销售单号"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="mp_code"
            label="计划单号"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column
            prop="inv_code"
            label="物料编码"
            align="center"
            width="120"
          >
          </el-table-column>
          <el-table-column label="物料名称" align="center">
            <template v-slot="scope">
              <div>
                <span
                  >{{ scope.row.inv_name }} {{ scope.row.inv_attribute }}</span
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column
            prop="unit_name"
            label="主计量"
            align="center"
            width="100"
          >
          </el-table-column>
          <el-table-column
            prop="surplus"
            label="数量"
            align="center"
            width="150"
          >
            <template v-slot="scope">
              <div style="text-align: right">
                <span>{{ scope.row.quantity }} </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单据日期" align="center" width="120">
            <template v-slot="scope">
              <span>{{ scope.row.invoice_date | inMaterTime }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding"
            width="120"
          >
            <template slot-scope="scope">
              <div class="public-btn">
                <el-button
                  size="mini"
                  type="text"
                  @click.stop="handleSuccess('detail', scope.row)"
                  >选择
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页 -->
      <pagination
        v-if="total > 0 && detailStatus == false"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getBillList"
      />
      <!-- 明细分页 -->
      <pagination
        v-if="detailTotal > 0 && detailStatus == true"
        :total="detailTotal"
        :page.sync="queryDetail.pageNum"
        :limit.sync="queryDetail.pageSize"
        @pagination="getDetailList"
      />
    </div>
    <div class="ImportMaterial-success" v-if="detailStatus == false">
      <div>
        <el-button
          :disabled="successStatus"
          type="primary"
          @click="handleSuccess('bill')"
          >确定</el-button
        >
        <el-button @click="handleClose">取消</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { listImportBill, listImportDetail, listBill } from "../../api/mbom";
let self;
export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 领料方式按钮文字
      typeTitle: "--",
      // 搜索单据
      searchForm: {
        ppNumber: "", //销售单号
        startDate: "",
        endDate: "",
        invName: "", //物料名称
        invCode: "", //物料编码
        mpCode: "",
      },
      //查询单据参数
      queryParams: {
        pageNum: 1,
        pageSize: 100,
        ppNumber: "",
        invName: "", //物料名称
        invCode: "", //物料编码
        startDate: "",
        endDate: "",
      },
      //明细状态
      detailStatus: false,

      tableKey: "1",
      // 总条数
      total: 0,
      // 最大高度
      maxHeight: null,
      //单据数据
      billTableData: [],
      //已选单据
      billSelected: [],
      //已选物料
      materialSelected: [],
      expands: [],
      successStatus: true,
      // 领料方式
      continuityStatus: false,
      //明细加载中
      detailLoding: true,
      //查询明细参数
      queryDetail: {
        mpCode: "",
        invCode: "",
        invName: "",
        startDate: "",
        endDate: "",
      },
      tableKey2: "2",
      //明细数据
      detailTableData: [],
      //明细条数
      detailTotal: 0,
      // 明细最大高度
      detailMaxHeight: null,
      // 开始时间/结束时间配置
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date(
                new Date(new Date().toLocaleDateString()).getTime()
              );
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      valueDate: [],
      successData: null,
      lableData:new Date().getTime
    };
  },
  props: {
    selectPrsCodeDialog: {
      type: Boolean,
      default: true,
    },
    optionsInvInType: {
      type: Array,
      default: () => {
        return [];
      },
    },
    gatherType: {
      type: String,
      default: "1",
    },
          // 小数位数
      decimal:{
        type:String,
        default:"2"
      }
  },
  beforeCreate() {
    self = this;
  },
  created() {
    this.getBillList();
  },

  methods: {
    // 获取单据
    getBillList() {
      this.loading = true;
      listImportBill(this.queryParams).then((res) => {
        if (res.code == 200) {
          this.expands = [];
          this.loading = false;
          res.rows.forEach((item) => {
            item.list = [];
          });
          this.billTableData = res.rows;
          this.total = res.total;
          this.maxHeight = `${document.documentElement.clientHeight}` - 390;
        }
      });
    },

    // 获取明细
    getDetailList() {
      return new Promise((resolve, reject) => {
        this.detailLoading = true;
        listImportDetail(this.queryDetail).then((res) => {
          if (res.code == 200) {
            this.detailLoading = false;
            this.detailTotal = res.total;
            this.getDecimal();
            this.detailMaxHeight = null;
            if (res.rows.length > 0) {
              this.detailTableData = res.rows;
              this.getDecimal();
            } else {
              this.$refs["tableDetailHeight"].doLayout();
              this.detailTableData = [];
            }

            this.detailMaxHeight =
              `${document.documentElement.clientHeight}` - 390;
          }
        });
      });
    },

    //搜索单据
    searchList(type) {
      // 日期转换
      if (
        this.valueDate !== undefined &&
        this.valueDate !== null &&
        this.valueDate.length > 0
      ) {
        if (this.detailStatus == false) {
          this.queryParams.startDate = this.parseTime(this.valueDate[0]);
          this.queryParams.endDate = this.setTime(this.valueDate[1]);
        } else {
          this.queryDetail.startDate = this.parseTime(this.valueDate[0]);
          this.queryDetail.endDate = this.setTime(this.valueDate[1]);
        }
      } else {
        if (this.detailStatus == false) {
          this.queryParams.startDate = "";
          this.queryParams.endDate = "";
        } else {
          this.queryDetail.startDate = "";
          this.queryDetail.endDate = "";
        }
      }
      if (type == "bill") {
        this.queryParams.ppNumber = this.searchForm.ppNumber;
        this.queryParams.invName = this.searchForm.invName;
        this.queryParams.invCode = this.searchForm.invCode;
        this.getBillList();
      } else if (type == "detail") {
        this.queryDetail.ppNumber = this.searchForm.ppNumber;
        this.queryDetail.invName = this.searchForm.invName;
        this.queryDetail.invCode = this.searchForm.invCode;
        this.queryDetail.mpCode = this.searchForm.mpCode;
        this.getDetailList();
      }
    },

    radioData(data) {
        this.successStatus = false;
        this.successData = data;
    },

    //点击中子
    clickRowRadio(row) {
      this.radioData(row);
    },

    // 清空单据/明细搜索条件
    checkClearAll() {
      return new Promise((resolve, reject) => {
        this.queryParams = {
          pageNum: 1,
          pageSize: 100,
          startDate: "",
          endDate: "",
          ppNumber: "",
          invName: "", //物料名称
          invCode: "", //物料编码
        };
        this.valueDate = [];
        // 搜索表单
        this.searchForm = {
          ppNumber: "",
          startDate: "",
          endDate: "",
          invName: "", //物料名称
          invCode: "", //物料编码
          mpCode: "",
        };
        this.queryDetail = {
          mpCode: "",
          pageNum: 1,
          pageSize: 100,
          ppNumber: "",
          invName: "",
          invCode: "",
          startDate: "",
          endDate: "",
        };
        this.successStatus = true;
        resolve();
      });
    },

    //查询所有明细
    handleCheckleDetail() {
      this.checkClearAll().then(() => {
        this.getDetailList().then(() => {
          this.$refs.tableDetailHeight.clearFilter();
        });
      });
    },

    // 查询所有单据
    handleCheckleAll() {
      this.checkClearAll().then(() => {
        this.getBillList();
      });
    },

    //展开获取物料信息
    handleExpand(row) {
      let loIndex = this.expands.indexOf(row.mp_code);
      if (loIndex < 0) {
        this.expands.push(row.mp_code);
      } else {
        this.expands.splice(loIndex, 1);
      }

      if (row.list.length == 0) {
        listBill({ mpOrderCode: row.mp_code,isBomCalc:true }).then((res) => {
          if (res.code == 200) {
            row.list = [];
            row.list = [...res.rows];
            this.getDecimal();
          }
        });
      } else {
        setTimeout(() => {
          if (this.billSelected.length > 0) {
            let code = this.billSelected[0].mp_code;
            if (
              this.billSelected.length > 0 &&
              this.materialSelected.length > 0 &&
              this.$refs["detailTable" + code] !== undefined
            ) {
              this.materialSelected.forEach((item) => {
                this.$refs["detailTable" + code].toggleRowSelection(item, true);
              });
            }
          }
        }, 0);
      }
    },

    // 切换领料
    handleContinuity() {
      if (this.detailStatus == false) {
        this.checkClearAll();
        this.detailStatus = true;
        this.getDetailList();
        this.typeTitle = "单据";
      } else {
        this.checkClearAll();
        this.getBillList();
        this.detailStatus = false;
        this.typeTitle = "明细";
      }
    },

    //批量选择单据
    handleParentChange(row) {
      let del_row;
      this.billSelected = [];
      if (row.length > 1) {
        del_row = row.shift(); //得到已删除的单据
        this.$nextTick(() => {
          this.$refs.billTable.toggleRowSelection(del_row, false);
        });
        // 清除已选中
        if (
          del_row.list.length > 0 &&
          this.$refs["detailTable" + del_row.mp_code] !== undefined
        ) {
          del_row.list.forEach((row) => {
            setTimeout(() => {
              this.$refs["detailTable" + del_row.mp_code].toggleRowSelection(
                row,
                false
              );
            }, 0);
          });
        }
      }

      this.billSelected = row; //核心->赋值单据
      if (row.length > 0) {
        if (row[0].list.length == 0) {
          //无物料数据，发送请求
          listBill({ mpOrderCode: row[0].mp_code,isBomCalc:true }).then((res) => {
            if (res.code == 200) {
              row[0].list = [...res.rows];
              this.getDecimal();
              //展开当前
              if (this.expands.indexOf(row[0].mp_code) < 0) {
                this.expands.push(row[0].mp_code);
              }
              this.materialSelected = row[0].list; //核心->赋值物料
              this.successStatus = false;
              this.handleCommon(row[0].mp_code, row[0].list, true);
            }
          });
        } else {
          //展开当前
          if (this.expands.indexOf(row[0].mp_code) < 0) {
            this.expands.push(row[0].mp_code);
          }
          this.materialSelected = row[0].list; //核心->赋值物料
          this.successStatus = false;
          this.handleCommon(row[0].mp_code, row[0].list, true);
        }
      } else {
        if (
          this.materialSelected.length > 0 &&
          this.$refs["detailTable" + this.materialSelected[0].mp_code] !==
            undefined
        ) {
          this.handleCommon(
            this.materialSelected[0].mp_code,
            this.materialSelected,
            false
          );
        }
        this.materialSelected = [];
        this.successStatus = true;
      }
    },

    //批量选择物料
    handleChildChange(row) {
      console.log(111);
      if (row.length > 0 && this.billSelected.length == 0) {
        this.billTableData.forEach((item) => {
          if (item.mp_code == row[0].mp_code) {
            this.billSelected[0] = item;
            this.$refs.billTable.toggleRowSelection(item, true);
          }
        });
      }

      //当没有选择单据，选择子物料信息时
      if (row.length > 0 && row[0].mp_code !== this.billSelected[0].mp_code) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], false);
        let code = this.billSelected[0].mp_code;
        if (this.$refs["detailTable" + code] !== undefined) {
          this.materialSelected.forEach((row) => {
            this.$refs["detailTable" + code].toggleRowSelection(row, false);
          });
        }

        this.billTableData.forEach((item) => {
          if (item.mp_code == row[0].mp_code) {
            this.billSelected[0] = item;
            this.$refs.billTable.toggleRowSelection(item, true);
          }
        });
      } else if (row.length == 0) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], false);
      } else if (
        row.length > 0 &&
        row[0].mp_code == this.billSelected[0].mp_code
      ) {
        this.$refs.billTable.toggleRowSelection(this.billSelected[0], true);
      }
      this.materialSelected = row;
      if (this.materialSelected.length > 0) {
        this.successStatus = false;
      } else {
        this.successStatus = true;
      }
    },

    //公用选择方法
    handleCommon(code, list, type) {
      this.$nextTick(() => {
        list.forEach((row) => {
          this.$refs["detailTable" + code].toggleRowSelection(row, type);
        });
      });
    },

    //格式化数量单价金额小数位数
    getDecimal() {
      if (this.billTableData.length > 0) {
        this.billTableData.forEach((obj) => {
          if (obj.list.length > 0) {
            obj.list.forEach((item) => {
              if (item.price !== null && item.price !== undefined) {
                item.price = parseFloat(item.price).toFixed(this.decimal);
              }
              if (item.surplus !== null && item.surplus !== undefined) {
                item.surplus = parseFloat(item.surplus).toFixed(this.decimal);
              }
              if (item.amount !== null && item.amount !== undefined) {
                item.amount = parseFloat(item.amount).toFixed(2);
              }
              if (item.invQuantity !== null && item.invQuantity !== undefined) {
                item.invQuantity = parseFloat(item.invQuantity).toFixed(
                  this.decimal
                );
              }
            });
          }
        });
      }
      if (this.detailTableData.length > 0) {
        this.detailTableData.forEach((item) => {
          if (item.surplus !== null && item.surplus !== undefined) {
            item.surplus = parseFloat(item.surplus).toFixed(this.decimal);
          }
          if (item.quantity !== null && item.quantity !== undefined) {
            item.quantity = parseFloat(item.quantity).toFixed(this.decimal);
          }
        });
      }
    },

    // 弹框状态
    selectPrsCodeClose() {
      this.$emit("selectPrsCodeClose");
    },

    //双击领料
    handleSelectDetail(row) {
      this.$emit(
        "handlePrsCodeSuccess",
        { detailStatus: this.detailStatus },
        row
      );
      this.selectPrsCodeClose();
    },

    //确定选取按单
    handleSuccess() {
      this.$emit("handlePrsCodeSuccess", this.successData);
      this.selectPrsCodeClose();
    },

    //点击展开行
    clickRowHandle(row) {
      this.handleExpand(row);
    },

    // 关闭弹框
    handleClose() {
      this.selectPrsCodeClose();
    },

    //时间+23时59分59秒
    setTime(date) {
      date.setHours(date.getHours() + 23);
      date.setMinutes(date.getMinutes() + 59);
      date.setSeconds(date.getSeconds() + 59);
      let time = new Date(date);
      return (
        time.getFullYear() +
        "-" +
        (time.getMonth() + 1) +
        "-" +
        time.getDate() +
        " " +
        time.getHours() +
        ":" +
        time.getMinutes() +
        ":" +
        time.getSeconds()
      );
    },
  },
  filters: {
    //时间格式化
    inMaterTime(date) {
      let time = new Date(date);
      return (
        time.getFullYear() + "-" + (time.getMonth() + 1) + "-" + time.getDate()
      );
    },

    //交期状态
    filterStatus(status) {
      switch (status) {
        case "0":
          return "预计";
          break;
        case "1":
          return "确认";
          break;
        default:
          return "";
      }
    },

    //匹配用料方式
    matchingInvType(data) {
      let supply = "";
      if (self.optionsInvInType && self.optionsInvInType.length > 0) {
        self.optionsInvInType.forEach((item) => {
          if (item.dictValue == data) {
            supply = item.dictLabel;
          }
        });
      }
      return supply;
    },
  },
};
</script>
<style lang="scss">
.prs-Mbom-select {
  .el-radio__label {
    display: none;
  }
  .el-dialog__body {
    height: calc(100vh - 250px);
    position: relative;
  }
  .el-table__body {
    user-select: none;
  }
  .is-plan {
    background: #67c23a !important;
    border-color: #67c23a !important;
    color: #ffffff !important;
    outline: none !important;
  }
  .el-range-editor--medium.el-input__inner {
    line-height: 32px;
  }
  .el-range-editor--medium .el-range__icon,
  .el-range-editor--medium .el-range__close-icon,
  .el-range-editor--medium .el-range-separator {
    line-height: 24px;
  }
  .el-range-editor--medium.el-input__inner {
    height: 32px;
  }
  .el-table--border {
    border-top: none;
  }
  .parent-table {
    th,
    td {
      border-right: 1px solid #dfe6ec;
    }
    th:nth-of-type(1),
    td:nth-of-type(1) {
      border-left: 1px solid #dfe6ec;
    }
  }
  .child-table {
    margin-bottom: 24.5px;
    margin-top: -5.5px;
    box-sizing: border-box;
  }

  .search-top {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }

  .el-pagination {
    left: 0;
  }

  .el-table__header-wrapper {
    .el-checkbox {
      display: none;
    }
  }
  .app-container {
    padding-top: 0;
  }

  .layout-box {
    .el-link.is-underline:hover:after {
      border: none;
    }

    .search-box {
      display: flex;
      margin-bottom: 20px;

      .search-input {
        display: flex;
        margin-right: 15px;

        .input-data {
          min-width: 220px !important;
        }

        .el-input {
          margin-right: 15px;
        }
      }
    }

    .sort-active {
      background: #1890ff !important;
      border-color: #1890ff !important;
      color: #ffffff !important;
    }

    .con-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .material-sort {
      span {
        font-size: 14px;
        padding: 0px 15px;
        background: #f4f4f5;
        color: #999;
        display: inline-block;
        border-radius: 3px;
        margin-left: 5px;
        margin-right: 5px;
        cursor: pointer;
        line-height: 26px;
        border: 1px solid #e9e9eb;
      }
    }
  }

  .ImportMaterial-success {
    position: absolute;
    bottom: 20px;
    right: 40px;

    button {
      padding: 8px 40px;
    }
  }
}
</style>
